// React懒加载功能
import { lazy } from "react";
// React Router相关功能
import { createBrowserRouter, Navigate } from "react-router-dom";
// Ant Design图标组件
import {
  SettingOutlined,
  VideoCameraOutlined,
  UserOutlined,
} from "@ant-design/icons";

// 直接导入的页面组件
import Login from "../pages/login/index";
import Home from "../pages/home/index";
import Indextow from '../pages/indextow/index'
// 懒加载的页面组件 - 提高应用性能
let Index = lazy(() => import("../pages/index/index"));
let Order = lazy(() => import("../pages/order/index"));
let User = lazy(() => import("../pages/user/index"));
let Indexone = lazy(() => import("../pages/index/indexone/index"));
let TextToSpeechDemo = lazy(() => import("../pages/demo/text-to-speech-demo"));


/**
 * 权限规则类型定义
 */
interface RuleType {
  router: string[];        // 可访问的路由列表
  mybtn: {
    index: string[];       // 首页可用的按钮权限
  };
}

// 动态路由数组
export const homeRouder = [];

/**
 * 路由配置对象 - 定义所有页面的路由信息
 */
const reacRouter = {
  // 首页路由配置
  index: {
    path: "/home/index",
    element: <Index />,
    title: "index",
    icon: <SettingOutlined />,
    children: [
      {
        path: "/home/index/indexone",
        element: <Indexone />,
        title: "indexone",
      },
      // 注释掉的路由配置
      // {
      //   path: "/indextow",
      //   element: <Navigate to="/indextow"></Navigate>,
      //   title: "indextow",
      // },
    ],
  },
  // 订单页面路由配置
  order: {
    path: "/home/order",
    element: <Order />,
    title: "order",
    icon: <VideoCameraOutlined />,
  },
  // 用户页面路由配置
  user: {
    path: "/home/user",
    element: <User />,
    title: "user",
    icon: <UserOutlined />,
  },
};

/**
 * 权限规则配置 - 根据用户角色控制路由和按钮权限
 */
const rules: Record<string, RuleType> = {
  // 管理员权限
  admin: {
    router: ["index", "order", "user"],  // 可访问所有页面
    mybtn: {
      index: ["add", "edit", "del"],     // 首页有增删改权限
    },
  },
  // 普通用户权限
  user: {
    router: ["index", "user"],           // 只能访问首页和用户页
    mybtn: {
      index: [],                         // 首页无特殊权限
    },
  },
};

// 根据用户角色获取对应的权限配置
const { router, mybtn } = rules[localStorage.getItem("role") || "admin"];

// 根据权限动态生成路由配置
router &&
  router.forEach((item) => {
    homeRouder.push({
      ...reacRouter[item],
      // 路由加载器：为每个路由提供按钮权限信息
      loader: () => {
        return { btns: mybtn[item] };
      },
    });
  });

/**
 * 主路由配置 - 使用createBrowserRouter创建浏览器路由
 */
const routes = createBrowserRouter([
  // 根路径重定向到首页
  {
    path: "/",
    element: <Navigate to="/home/index/indexone"></Navigate>,
  },
  // 主布局页面
  {
    path: "/home",
    element: <Home />,
    children: homeRouder,  // 子路由通过权限动态生成
  },
  // 独立页面路由
  {
    path: "/indextow",
    element: <Indextow />,
    // title: "indextow",
  },
  // 登录页面路由
  {
    path: "/login",
    element: <Login />,
  },
  // 文字转语音演示页面
  {
    path: "/demo/text-to-speech",
    element: <TextToSpeechDemo />,
  },
]);

// 导出路由配置
export default routes;
